import { localCache } from '@/utils';
import { firstMenu } from '@/utils/map-menus';
import { RouteRecordRaw, createRouter, createWebHashHistory } from 'vue-router';

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/main'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login/login.vue')
  },
  {
    path: '/main',
    name: 'main',
    component: () => import('../views/main/main.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'notFound',
    component: () => import('@/views/not-found/not-found.vue')
  }
];

const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes
});

router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    next();
  } else {
    const token = localCache.getCache('token');
    if (token) {
      if (to.path === '/main') {
        next(firstMenu.url);
      }
      next();
    } else {
      next('/login');
    }
  }
});

export default router;
